<template>
  <n-modal
    v-model:show="showLiveStreamModal"
    preset="card"
    title="直播流"
    style="width: 800px"
    @close="handleClose"
  >
    <div class="video-container">
      <video
        ref="videoPlayer"
        class="video-js vjs-default-skin"
      ></video>
    </div>
  </n-modal>
</template>

<script lang="ts">
import { defineComponent, ref, watch, onMounted, onBeforeUnmount } from 'vue';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import 'videojs-flvjs-es6';
import flvjs from 'flv.js';

export default defineComponent({
  props: {
    url: {
      type: String,
      required: true
    },
    show: {
      type: Boolean,
      required: true
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const videoPlayer = ref<HTMLVideoElement | null>(null);
    const showLiveStreamModal = ref(props.show);
    let player: any = null;

    // 监听show prop变化
    watch(() => props.show, (newVal) => {
      showLiveStreamModal.value = newVal;
    });

    // 初始化播放器
    onMounted(() => {
      if (videoPlayer.value) {
        const isFLV = props.url.endsWith('.flv');
        if(isFLV){
          player = videojs(videoPlayer.value, {
            autoplay: true,
            controls: true,
            fluid: true,
            liveui: true,
            html5: {
              hls: {
                overrideNative: true
              },
              flvjs: {
                mediaDataSource: {
                  isLive: true,
                  cors: true,
                  withCredentials: false
                }
              }
            },
            sources: [{
              src: props.url,
              type: isFLV ? 'video/x-flv' : 'application/x-mpegURL'
            }]
          });
        }else{

          player = videojs(videoPlayer.value, {
            autoplay: true,
            controls: true,
            fluid: true,
            liveui: true,
            html5: {
              hls: {
                overrideNative: true
              }
            },
            sources: [{
              src: props.url,
              type: 'application/x-mpegURL'
            }]
          });
        }
      }
    });

    // 清理播放器
    onBeforeUnmount(() => {
      if (player) {
        player.dispose();
      }
    });

    // 处理关闭事件
    const handleClose = () => {
      showLiveStreamModal.value = false;
      emit('close');
    };

    return {
      videoPlayer,
      showLiveStreamModal,
      handleClose
    };
  }
});


</script>

<style scoped>
.video-container {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 aspect ratio */
  height: 0;
  overflow: hidden;
}

.video-js {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
